package com.icefish.control;

import com.alibaba.fastjson.JSONObject;
import com.icefish.bean.User;

import com.icefish.bean.fastjsonParse.Meta;
import com.icefish.bean.fastjsonParse.login.User_token;
import com.icefish.bean.fastjsonParse.login.loginResp;
import com.icefish.dao.UserDao;
import com.icefish.daoFactory.DaoFactory;
import com.icefish.utils.Init_Req_Resp_Config;
import com.icefish.utils.JWT_Utile;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 登录验证
@WebServlet( "/login")
public class login extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 标准配置
        Init_Req_Resp_Config.init(request, response);
        // 捞取请求数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = null;
        boolean loginflag = false;
        Meta meta = null;
        User_token data = null;
        loginResp lp = null;

        // 1、查询users表，检查账户密码是否正确
        UserDao userdao = DaoFactory.getUserDaoInstance();
        try {
            Integer user_id = userdao.selectByNamePWD(username,password);
            user = userdao.selectByID(user_id);

            if (user != null) {
                loginflag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 2.1、JWT加密
        String token = JWT_Utile.CreatToken(user);

        // 2.2、响应JSON数据

        // 登录成功
        if (loginflag) {
            meta = new Meta("登录成功",200);
            data = new User_token(user,token);
            lp = new loginResp(data,meta);
        } else {
            // 登录失败
            meta = new Meta("登录失败",200);
            data = new User_token(user,token);
            lp = new loginResp(data,meta);
        }

        JSONObject jsonObject = new JSONObject();
        // 转换成json
        String backToBrowser = jsonObject.toJSONString(lp);

        // 响应数据
        response.getWriter().write(backToBrowser);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
